import json
import time
import hashlib
import requests
import uuid
import socket
import logging, pdb
from random import Random
from user.models import User, VSession


def randomNumber(length=20):
    string = ''
    chars = '0123456789'
    random = Random()
    for i in range(length):
        string += chars[random.randint(0, len(chars) - 1)]
    return string


class DataCheck():
    # 模块验证数据是否合法

    def userId(self, requestParam):
        # 设置初始验证值
        isValidOk = True
        errMsg = ''
        # 验证用户id必须存在
        user = User.objects.filter(pk=requestParam['userId'])
        if isValidOk and (not user.exists()):
            errMsg = 'userId Error'
            isValidOk = False
        return isValidOk, errMsg

    def getLocalToken(self):
        m = hashlib.md5()
        m.update(bytes(str(time.time()), encoding='utf-8'))
        return m.hexdigest()[0:20]

    def getUser(self, token):
        sessionList = VSession.objects.filter(token=token)
        session = sessionList[0]
        user = session.user
        return user


    def getIP(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip
